#include <hpdf.h>
#include <stdio.h>

#define MARGIN 50.0       // 页边距
#define FONT_SIZE 27.0    // 字体大小
#define CHAR_PER_LINE 15  // 每行字符数
#define CHAR_PER_PAGE 300 // 每页字符数

void generate_chars(HPDF_Doc pdf, HPDF_Page page, HPDF_Font font) {
    int area = 16;   // GB2312汉字区从16区开始
    int count = 0;
    float x = MARGIN;
    float y = HPDF_Page_GetHeight(page) - MARGIN - FONT_SIZE; // 使用 HPDF_Page_GetHeight 获取页面高度
    float line_height = FONT_SIZE + 5; // 行间距

    for (; area <= 87; area++) {  // GB2312汉字区到87区
        for (int pos = 1; pos <= 94; pos++) {  // 每个区94个位
            unsigned char buf[3] = {
                (unsigned char)(area + 0xA0),
                (unsigned char)(pos + 0xA0),
                0
            };

            HPDF_Page_BeginText(page);
            HPDF_Page_SetFontAndSize(page, font, FONT_SIZE);
            HPDF_Page_TextOut(page, x, y, (const char*)buf);
            HPDF_Page_EndText(page);

            x += FONT_SIZE + 5; // 字符间距
            if (++count % CHAR_PER_LINE == 0) {  // 每行15字
                x = MARGIN;
                y -= line_height;
            }
            if (count % CHAR_PER_PAGE == 0) {  // 每页300字
                page = HPDF_AddPage(pdf);
                HPDF_Page_SetSize(page, HPDF_PAGE_SIZE_A4, HPDF_PAGE_PORTRAIT);
                x = MARGIN;
                y = HPDF_Page_GetHeight(page) - MARGIN - FONT_SIZE; // 重新计算 y
            }
        }
    }
}

int main() {
    HPDF_Doc pdf = HPDF_New(NULL, NULL);
    if (!pdf) {
        printf("Error: Cannot create PDF document.\n");
        return 1;
    }

    HPDF_UseCNSEncodings(pdf);
    HPDF_UseCNSFonts(pdf);

    HPDF_Page page = HPDF_AddPage(pdf);
    HPDF_Page_SetSize(page, HPDF_PAGE_SIZE_A4, HPDF_PAGE_PORTRAIT);

    HPDF_Font font = HPDF_GetFont(pdf, "SimSun", "GBK-EUC-H");
    if (!font) {
        printf("Error: Cannot load font.\n");
        HPDF_Free(pdf);
        return 1;
    }

    generate_chars(pdf, page, font);

    HPDF_SaveToFile(pdf, "宋体汉字.pdf");
    HPDF_Free(pdf);
    return 0;
}